# -*- encoding: utf-8 -*-

"""
 This is 
 Create by fuwei 2018/12/18

 验证SSO权限
 
"""

import urlparse
from config import configure
from app.main.src.public import http_json_request, parse_cookie
from app.main.src.cluster.cluster_config import ClusterConfig
from app.main.src.public import RedisCache
import json
from logs.log import logger
from flask import request, jsonify

# Redis Cache KEY type
USER_ENV_TYPE = 2
USER_PRODUCT_TYPE = 3


class UserAuth(object):
    def __init__(self, user_name, pm_name='Project'):
        """
        :param user_name: 用户名
        :param pm_name: SSO项目名称
        """
        self.user_name = user_name
        self.pm_name = pm_name
        self.redis_cache = RedisCache(username=self.user_name, pm_name=self.pm_name)
        self.redis_key_ttl = 180

    def get_user_env(self):
        """
        :return: []
        """
        # 先从Redis里面读
        data = self.redis_cache.get_cache(cache_type=USER_ENV_TYPE)

        # 如果Redis没有，从项目中心读并设置一存在Redis
        if data is None:
            url = urlparse.urljoin(configure.SSO_API, "/get_user_pm_env/")
            params = dict(user_name=self.user_name, pm_name=self.pm_name)
            data = http_json_request(url, method="GET", data=params)

            self.redis_cache.set_cache(cache_type=USER_ENV_TYPE, data=data, ttl=self.redis_key_ttl)
        print(data)
        # 直接返回Redis中的数据
        if data['status'] is True:
            return data['info']
        else:
            return []

    def get_user_product(self):
        """
        :return: []
        """
        # 先从Redis里面读
        data = self.redis_cache.get_cache(cache_type=USER_PRODUCT_TYPE)

        # 如果Redis没有，从项目中心读并设置一存在Redis
        if data is None:
            url = urlparse.urljoin(configure.SSO_API, "/get_user_pm_product/")
            params = dict(user_name=self.user_name, pm_name=self.pm_name)
            data = http_json_request(url, method="GET", data=params)

            self.redis_cache.set_cache(cache_type=USER_PRODUCT_TYPE, data=data, ttl=self.redis_key_ttl)

        # 直接返回Redis中的数据
        if data['status'] is True:
            return data['info']
        else:
            return []


class NotFund(Exception):
    pass


class PermFail(Exception):
    pass


def validate_user_pri(user_name, env, cluster_name, pm_name="Project"):
    """
    验证用户环境和项目权限
    :param user_name:
    :param env:
    :param cluster_name:
    :param pm_name:
    :return:
    """

    # 验证操作环境的权限
    user_auth = UserAuth(user_name=user_name, pm_name=pm_name)
    user_env_list = user_auth.get_user_env()
    user_product_list = user_auth.get_user_product()

    if env not in user_env_list:
        data = u'你没有操作 {env} 环境权限'.format(env=env)
        logger.info(data)
        raise PermFail(data)

    # 验证项目的权限
    if cluster_name:
        try:
            project_config = ClusterConfig(env=env, cluster_name=cluster_name)
        except Exception as e:
            raise NotFund(e)

        project_product = project_config.project_busline

        if project_product not in user_product_list:
            data = '你没有操作 {cluster_name} 环境权限'.format(cluster_name=cluster_name)
            logger.info(data)
            raise PermFail(data)



if __name__ == '__main__':
    print validate_user_pri(env='qa', cluster_name='ops-test', user_name='zuowenhong')
    # get_user_env("fuwei")
    # get_user_product("fuwei")
    # configer = ClusterConfig(
    #     env='qa',
    #     cluster_name='loan-manager-web',
    #     branch='ceshi',
    #     namespace='qb-qa-1'
    # )
    # print configer.get_other_name()
